/**
 * Created by ylc on 2017/5/17.
 */
import { baseUrl } from './env'
import 'fetch-detector'
import 'fetch-ie8'

require('es6-promise/auto')

export default async (type = 'GET', url = '', data = {}, method = 'fetch') => {
  type = type.toUpperCase()
  url = baseUrl + url

  if (type === 'GET') {
    let dataStr = '' // 数据拼接字符串
    Object.keys(data).forEach(key => {
      dataStr += key + '=' + data[key] + '&'
    })

    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
      url = url + '?' + dataStr
    }
  }
  // 暂时没有走fetch方法  需要与后端联调传参数据格式
  let a = 0
  if (window.fetch && method === 'fetch' && a === 1) {
    let requestConfig = {
      //  credentials: 'include',
      method: type,
      headers: {
        Accept: 'application/json, text/javascript, */*; q=0.01',
        'Content-Type': 'application/json; charset=UTF-8'
      },
      mode: 'cors'
      //     cache: "default"
    }

    if (type === 'POST') {
      let str = ''
      Object.keys(data).forEach(key => {
        str += key + '=' + data[key] + '&'
      })
      Object.defineProperty(requestConfig, 'body', {
        value: str
      })
    }

    try {
      var response = await fetch(url, requestConfig)
      var responseJson = await response.json()
    } catch (error) {
      throw new Error(error)
    }
    return responseJson
  } else {
    return new Promise((resolve, reject) => {
      let requestObj = new XMLHttpRequest()
      let sendData = ''
      if (type === 'POST' || 'PUT') {
        sendData = JSON.stringify(data)
      }
      console.log(sendData)
      requestObj.open(type, url, true)
      requestObj.setRequestHeader('Content-type', 'application/json')
      requestObj.send(sendData)

      requestObj.onreadystatechange = () => {
        if (requestObj.readyState === 4) {
          if (requestObj.status === 200) {
            let obj = requestObj.response
            if (typeof obj !== 'object') {
              obj = JSON.parse(obj)
            }
            resolve(obj)
          } else {
            reject(requestObj)
          }
        }
      }
    })
  }
}
